package com.six.clinic.common.custom_enum;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: shinan
 * @Version: 1.8
 * @create: 2020/11/30 20:19
 * @Description: 科室
 */
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@Getter
@AllArgsConstructor
public enum Department {
    /**
     * 全科
     */
    ALL(0, "全科"),
    /**
     * 儿科
     */
    CHILD(1, "儿科"),
    /**
     * 内科
     */
    IN(2, "内科");

    private final Integer value;

    private final String department;

    /**
     * 用于保存所有的枚举值
     */
    private static Map<String, Department> RESOURCE_MAP = Stream
            .of(Department.values())
            .collect(Collectors.toMap(s -> s.getDepartment(), Function.identity()));

    /**
     * 枚举反序列话调用该方法
     * @param jsonNode
     * @return
     */
    @JsonCreator
    public static Department des(final JsonNode jsonNode) {
        return Optional
                .ofNullable(RESOURCE_MAP.get(jsonNode.get("department").asText()))
                .orElseThrow(() -> new IllegalArgumentException(jsonNode.get("department").asText()));
    }


    public static Department getEnum(Integer value) {
        for (Department department : Department.values()) {
            if (department.getValue().equals(value)) {
                return department;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }

}
